#include "line.h"
#include <QPainterPath>
#include <cmath>

Line::Line(const QPointF &startPoint, const QPointF &endPoint, const QColor &color)
    : MyShape(startPoint, color), endPoint_(endPoint) {}

QRectF Line::boundingRect() const
{
    qreal minX = qMin(startPoint_.x(), endPoint_.x()) - hitRadius_ - penWidth_;
    qreal minY = qMin(startPoint_.y(), endPoint_.y()) - hitRadius_ - penWidth_;
    qreal maxX = qMax(startPoint_.x(), endPoint_.x()) + hitRadius_ + penWidth_;
    qreal maxY = qMax(startPoint_.y(), endPoint_.y()) + hitRadius_ + penWidth_;

    return QRectF(minX, minY, maxX - minX, maxY - minY);
}

void Line::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(option);
    Q_UNUSED(widget);

    painter->setPen(QPen(color_, penWidth_));
    painter->drawLine(startPoint_, endPoint_);

    if (isSelected_ || startHighlighted_ || endHighlighted_) {
        painter->setPen(QPen(Qt::blue, penWidth_));
        painter->setBrush(QBrush(Qt::blue));

        if (startHighlighted_ || isSelected_) {
            painter->drawEllipse(startPoint_, hitRadius_/2, hitRadius_/2);
        }

        if (endHighlighted_ || isSelected_) {
            painter->drawEllipse(endPoint_, hitRadius_/2, hitRadius_/2);
        }
    }
}

bool Line::isPointNear(const QPointF &point) const
{
    QLineF line(startPoint_, endPoint_);
    if (line.length() < 1e-6) return false;

    qreal dotProduct = (point.x()-startPoint_.x())*(endPoint_.x()-startPoint_.x()) +
                       (point.y()-startPoint_.y())*(endPoint_.y()-startPoint_.y());
    qreal normalized = dotProduct / (line.length() * line.length());

    if (normalized < 0 || normalized > 1) return false;

    QPointF projected(startPoint_.x() + normalized*(endPoint_.x()-startPoint_.x()),
                      startPoint_.y() + normalized*(endPoint_.y()-startPoint_.y()));

    return QLineF(point, projected).length() <= hitRadius_;
}

void Line::highlightControlPoints(const QPointF &point)
{
    startHighlighted_ = QLineF(startPoint_, point).length() <= hitRadius_;
    endHighlighted_ = QLineF(endPoint_, point).length() <= hitRadius_;
}
